<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${task != null ? '编辑文件同步任务 - ' + task.name : '新建文件同步任务'} + ' - 同步平台'"></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/}">
                                <i class="bi bi-house"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/dashboard}">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/server}">
                                <i class="bi bi-server"></i> 服务器管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/database}">
                                <i class="bi bi-database"></i> 数据库管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/database}">
                                <i class="bi bi-arrow-left-right"></i> 数据库同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" th:href="@{/sync/file}">
                                <i class="bi bi-files"></i> 文件同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/restore}">
                                <i class="bi bi-arrow-counterclockwise"></i> 数据库恢复
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/task/log}">
                                <i class="bi bi-list-check"></i> 同步日志
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2" th:text="${task != null ? '编辑文件同步任务' : '新建文件同步任务'}"></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a th:href="@{/sync/file}" class="btn btn-sm btn-outline-secondary">
                            <i class="bi bi-arrow-left"></i> 返回列表
                        </a>
                    </div>
                </div>
                
                <div class="alert alert-danger" id="errorAlert" style="display: none;"></div>
                <div class="alert alert-success" id="successAlert" style="display: none;"></div>
                
                <form id="taskForm" class="needs-validation" novalidate>
                    <input type="hidden" id="taskId" th:value="${task != null ? task.id : ''}">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="taskName" class="form-label">任务名称</label>
                            <input type="text" class="form-control" id="taskName" th:value="${task != null ? task.name : ''}" required>
                            <div class="invalid-feedback">请输入任务名称</div>
                        </div>
                        <div class="col-md-6">
                            <label for="taskStatus" class="form-label">任务状态</label>
                            <select class="form-select" id="taskStatus">
                                <option value="1" th:selected="${task != null && task.status == 1}">启用</option>
                                <option value="0" th:selected="${task != null && task.status == 0}">禁用</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="sourceServer" class="form-label">源服务器</label>
                            <select class="form-select" id="sourceServer" required>
                                <option value="">选择源服务器</option>
                                <option th:each="server : ${servers}" 
                                        th:value="${server.id}" 
                                        th:text="${server.name}" 
                                        th:selected="${task != null && task.sourceId == server.id}"></option>
                            </select>
                            <div class="invalid-feedback">请选择源服务器</div>
                        </div>
                        <div class="col-md-6">
                            <label for="targetServer" class="form-label">目标服务器</label>
                            <select class="form-select" id="targetServer" required>
                                <option value="">选择目标服务器</option>
                                <option th:each="server : ${servers}" 
                                        th:value="${server.id}" 
                                        th:text="${server.name}"
                                        th:selected="${task != null && task.targetId == server.id}"></option>
                            </select>
                            <div class="invalid-feedback">请选择目标服务器</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="transferType" class="form-label">传输方式</label>
                            <select class="form-select" id="transferType">
                                <option value="ssh" th:selected="${task != null && task.config != null && #strings.arraySplit(task.config, '|').length > 3 && #strings.arraySplit(task.config, '|')[3] == 'ssh'}">SSH/SFTP</option>
                                <option value="ftp" th:selected="${task != null && task.config != null && #strings.arraySplit(task.config, '|').length > 3 && #strings.arraySplit(task.config, '|')[3] == 'ftp'}">FTP</option>
                            </select>
                            <div class="form-text">选择文件传输协议</div>
                        </div>
                        <div class="col-md-6">
                            <label for="deleteSource" class="form-label">传输后删除源文件</label>
                            <select class="form-select" id="deleteSource">
                                <option value="false" th:selected="${task == null || task.config == null || #strings.arraySplit(task.config, '|').length <= 4 || #strings.arraySplit(task.config, '|')[4] != 'true'}">否</option>
                                <option value="true" th:selected="${task != null && task.config != null && #strings.arraySplit(task.config, '|').length > 4 && #strings.arraySplit(task.config, '|')[4] == 'true'}">是</option>
                            </select>
                            <div class="form-text">传输完成后是否删除源文件</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="sourcePath" class="form-label">源路径</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="sourcePath" th:value="${task != null && task.config != null ? #strings.arraySplit(task.config, '|')[0] : ''}" required>
                                <button class="btn btn-outline-secondary" type="button" id="browseSourcePath">
                                    <i class="bi bi-folder2-open"></i> 浏览
                                </button>
                            </div>
                            <div class="form-text">源服务器上的文件夹路径，例如：/home/user/data</div>
                            <div class="invalid-feedback">请输入源路径</div>
                        </div>
                        <div class="col-md-6">
                            <label for="targetPath" class="form-label">目标路径</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="targetPath" th:value="${task != null && task.config != null ? #strings.arraySplit(task.config, '|')[1] : ''}" required>
                                <button class="btn btn-outline-secondary" type="button" id="browseTargetPath">
                                    <i class="bi bi-folder2-open"></i> 浏览
                                </button>
                            </div>
                            <div class="form-text">目标服务器上的文件夹路径，例如：/home/user/backup</div>
                            <div class="invalid-feedback">请输入目标路径</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="filePattern" class="form-label">文件过滤表达式</label>
                            <input type="text" class="form-control" id="filePattern" th:value="${task != null && task.config != null && #strings.arraySplit(task.config, '|').length > 2 ? #strings.arraySplit(task.config, '|')[2] : ''}">
                            <div class="form-text">可选，支持通配符，例如：*.txt,*.log 或 data*.csv（留空则同步所有文件）</div>
                        </div>
                        <div class="col-md-6">
                            <label for="cronExpression" class="form-label">定时表达式（Cron）</label>
                            <input type="text" class="form-control" id="cronExpression" th:value="${task != null ? task.cronExpression : ''}">
                            <div class="form-text">可选，Cron表达式，例如：0 0 2 * * ? （每天凌晨2点执行）</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="syncDirectories" 
                                    th:checked="${task != null && task.config != null && #strings.arraySplit(task.config, '|').length > 5 && #strings.arraySplit(task.config, '|')[5] == 'true'}">
                                <label class="form-check-label" for="syncDirectories">
                                    同步目录结构
                                </label>
                                <div class="form-text">启用后将保持目录结构，同步整个目录树</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end mb-4">
                        <button type="button" id="testButton" class="btn btn-outline-primary me-md-2">
                            <i class="bi bi-check-circle"></i> 测试连接
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-save"></i> 保存任务
                        </button>
                    </div>
                </form>
            </main>
        </div>
    </div>
    
    <!-- 目录浏览模态框 -->
    <div class="modal fade" id="directoryBrowserModal" tabindex="-1" aria-labelledby="directoryBrowserModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="directoryBrowserModalLabel">浏览服务器目录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger" id="browserErrorAlert" style="display: none;"></div>
                    
                    <ol class="breadcrumb" id="directoryBreadcrumb">
                        <li class="breadcrumb-item active" data-path="/">根目录</li>
                    </ol>
                    
                    <div class="list-group" id="directoryList">
                        <!-- 目录列表将在这里动态生成 -->
                        <div class="d-flex justify-content-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="selectDirectoryBtn">选择当前目录</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.min.js"></script>
    <script th:src="@{/js/script.js}"></script>
    <script>
        $(document).ready(function() {
            // Form validation
            const form = document.getElementById('taskForm');
            form.addEventListener('submit', function(event) {
                event.preventDefault();
                
                if (!form.checkValidity()) {
                    event.stopPropagation();
                    form.classList.add('was-validated');
                    return;
                }
                
                // Get form data
                const taskData = {
                    id: $('#taskId').val() || null,
                    name: $('#taskName').val(),
                    taskType: 2, // File sync type
                    sourceId: $('#sourceServer').val(),
                    targetId: $('#targetServer').val(),
                    cronExpression: $('#cronExpression').val(),
                    status: $('#taskStatus').val()
                };
                
                const sourcePath = $('#sourcePath').val();
                const targetPath = $('#targetPath').val();
                const filePattern = $('#filePattern').val();
                const transferType = $('#transferType').val();
                const deleteSource = $('#deleteSource').val();
                
                // Save task with all parameters in one request
                $.ajax({
                    url: '/sync/file/save',
                    type: 'POST',
                    data: {
                        // Task basic data
                        id: taskData.id,
                        name: taskData.name,
                        taskType: taskData.taskType,
                        sourceId: taskData.sourceId,
                        targetId: taskData.targetId,
                        cronExpression: taskData.cronExpression,
                        status: taskData.status,
                        // Additional parameters
                        sourcePath: sourcePath,
                        targetPath: targetPath,
                        filePattern: filePattern,
                        transferType: transferType,
                        deleteSource: deleteSource,
                        syncDirectories: $('#syncDirectories').is(':checked')
                    },
                    success: function(result) {
                        if (result.success) {
                            $('#successAlert').text('保存成功').show();
                            setTimeout(function() {
                                window.location.href = '/sync/file';
                            }, 1500);
                        } else {
                            $('#errorAlert').text('保存失败：' + (result.message || '未知错误')).show();
                        }
                    },
                    error: function() {
                        $('#errorAlert').text('保存失败：服务器错误').show();
                    }
                });
            });
            
            // Test connection
            $('#testButton').click(function() {
                const sourceId = $('#sourceServer').val();
                const targetId = $('#targetServer').val();
                
                if (!sourceId || !targetId) {
                    $('#errorAlert').text('请选择源服务器和目标服务器').show();
                    return;
                }
                
                const btn = $(this);
                btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 测试中...');
                
                // TODO: Implement test connection functionality
                setTimeout(function() {
                    $('#successAlert').text('连接测试成功').show();
                    btn.prop('disabled', false).html('<i class="bi bi-check-circle"></i> 测试连接');
                }, 1500);
            });
            
            // Hide alerts when input changes
            $('input, select').on('change', function() {
                $('#errorAlert').hide();
                $('#successAlert').hide();
            });
            
            // 目录浏览功能
            let currentServerId = null;
            let currentPath = '/';
            let targetInput = null;
            
            // 初始化目录浏览模态框
            const directoryBrowserModal = new bootstrap.Modal(document.getElementById('directoryBrowserModal'));
            
            // 源路径浏览按钮点击事件
            $('#browseSourcePath').click(function() {
                const sourceServerId = $('#sourceServer').val();
                if (!sourceServerId) {
                    $('#errorAlert').text('请先选择源服务器').show();
                    return;
                }
                
                targetInput = $('#sourcePath');
                initDirectoryBrowser(sourceServerId, targetInput.val() || '/');
                $('#directoryBrowserModalLabel').text('浏览源服务器目录');
                directoryBrowserModal.show();
            });
            
            // 目标路径浏览按钮点击事件
            $('#browseTargetPath').click(function() {
                const targetServerId = $('#targetServer').val();
                if (!targetServerId) {
                    $('#errorAlert').text('请先选择目标服务器').show();
                    return;
                }
                
                targetInput = $('#targetPath');
                initDirectoryBrowser(targetServerId, targetInput.val() || '/');
                $('#directoryBrowserModalLabel').text('浏览目标服务器目录');
                directoryBrowserModal.show();
            });
            
            // 初始化目录浏览器
            function initDirectoryBrowser(serverId, path) {
                currentServerId = serverId;
                $('#browserErrorAlert').hide();
                $('#directoryList').html('<div class="d-flex justify-content-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>');
                
                // 设置面包屑导航
                updateBreadcrumb(path);
                
                // 加载目录内容
                loadDirectoryContents(serverId, path);
            }
            
            // 加载目录内容
            function loadDirectoryContents(serverId, path) {
                currentPath = path;
                
                $.ajax({
                    url: '/sync/file/browse-directory',
                    type: 'GET',
                    data: {
                        serverId: serverId,
                        path: path
                    },
                    success: function(result) {
                        if (result.success) {
                            displayDirectories(result.directories, result.currentPath);
                        } else {
                            $('#browserErrorAlert').text(result.message || '加载目录失败').show();
                            $('#directoryList').html('<div class="alert alert-info">无法加载目录内容</div>');
                        }
                    },
                    error: function() {
                        $('#browserErrorAlert').text('服务器错误，无法加载目录内容').show();
                        $('#directoryList').html('<div class="alert alert-info">无法加载目录内容</div>');
                    }
                });
            }
            
            // 显示目录内容
            function displayDirectories(directories, currentPath) {
                let html = '';
                
                if (directories.length === 0) {
                    html = '<div class="alert alert-info">该目录下没有子目录</div>';
                } else {
                    for (let dir of directories) {
                        html += `
                        <a href="javascript:void(0)" class="list-group-item list-group-item-action directory-item" data-path="${dir.path}/">
                            <i class="bi bi-folder-fill me-2"></i> ${dir.name}
                        </a>`;
                    }
                }
                
                $('#directoryList').html(html);
                
                // 点击目录项事件
                $('.directory-item').click(function() {
                    const path = $(this).data('path');
                    loadDirectoryContents(currentServerId, path);
                    updateBreadcrumb(path);
                });
            }
            
            // 更新面包屑导航
            function updateBreadcrumb(path) {
                let parts = path.split('/').filter(part => part !== '');
                let html = '<li class="breadcrumb-item"><a href="javascript:void(0)" data-path="/">根目录</a></li>';
                let currentPath = '/';
                
                for (let i = 0; i < parts.length; i++) {
                    currentPath += parts[i] + '/';
                    if (i === parts.length - 1) {
                        html += `<li class="breadcrumb-item active">${parts[i]}</li>`;
                    } else {
                        html += `<li class="breadcrumb-item"><a href="javascript:void(0)" data-path="${currentPath}">${parts[i]}</a></li>`;
                    }
                }
                
                $('#directoryBreadcrumb').html(html);
                
                // 点击面包屑导航项事件
                $('#directoryBreadcrumb a').click(function() {
                    const path = $(this).data('path');
                    loadDirectoryContents(currentServerId, path);
                    updateBreadcrumb(path);
                });
            }
            
            // 选择当前目录按钮点击事件
            $('#selectDirectoryBtn').click(function() {
                if (targetInput) {
                    targetInput.val(currentPath);
                }
                directoryBrowserModal.hide();
            });
        });
    </script>
</body>
</html> 